package com.skz.web;

import cn.zhouyafeng.itchat4j.api.WechatTools;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author nullp
 */
@RequestMapping("/groups")
@RestController
public class GroupController {

    @GetMapping
    public ResponseEntity<List<JSONObject>> getGroup() {
        List<JSONObject> groupList = WechatTools.getGroupList();
        return ResponseEntity.ok(groupList);
    }

    @GetMapping("/{id}/members")
    public ResponseEntity<JSONArray> getGroup(@PathVariable String id) {
        JSONArray memberListByGroupId = WechatTools.getMemberListByGroupId(id);
        return ResponseEntity.ok(memberListByGroupId);
    }

    @GetMapping("/repeat")
    public ResponseEntity<List<MemberDto>> getRepeatMembers() {
        // 去重微信群
        List<JSONObject> groupList = WechatTools.getGroupList();
        Map<String, String> groups = new HashMap<>();
        groupList.forEach(jsonObject -> {
            String id = jsonObject.getString("UserName");
            String name = jsonObject.getString("NickName");
            groups.put(id, name);
        });
        //获取所有群成员
        List<MemberDto> list = new ArrayList<>();
        groups.forEach((id, name) -> {
            JSONArray members = WechatTools.getMemberListByGroupId(id);
            for (int i = 0; i < members.size(); i++) {
                JSONObject member = members.getJSONObject(i);
                String userId = member.getString("UserName");
                String displayName = member.getString("DisplayName");
                String nickName = member.getString("NickName");
                MemberDto repeatMemberDto = new MemberDto(userId, nickName, displayName, id, name);
                list.add(repeatMemberDto);
            }
        });
        //重复检测
        Map<String, List<MemberDto>> collect = list.stream().collect(Collectors.groupingBy(MemberDto::getId));
        List<MemberDto> resultList = new ArrayList<>(100);
        collect.forEach((s, members) -> {
            if (members.size() > 1) {
                resultList.addAll(members);
            }
        });
        return ResponseEntity.ok(resultList);
    }

}

